//
//  YYAirticleDetailViewController.swift
//  STMusic
//
//  Created by stoneobs on 2017/6/12.
//  Copyright © 2017年 stoneobs. All rights reserved.
// 文章详情

import UIKit
import WebKit
class YYAirticleDetailViewController: UIViewController,WKNavigationDelegate,YYMusicPlayListViewDelegate{
    
    //headerView 
    var bannerImageView:UIImageView?
    
    var playListView:YYMusicPlayListView?
    
    var titileView:YYTitleView?
    

    var scrollView:UIScrollView?
    
    var webView:WKWebView! = WKWebView.init(frame: .init(x: 30, y: 0, width: SCREEN_WIDTH - 30, height: SCREEN_HEIGHT));
    
    var model:YYArticleModel? = YYArticleModel();
    
    var detailModel:YYArticleDetailModel? = YYArticleDetailModel();
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white;
        self.automaticallyAdjustsScrollViewInsets = false;
        //webview 自适应
        let config = WKWebViewConfiguration()
        let jsstring = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'minimum-scale=1, maximum-scale=1.0,initial-scale=0.8,width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        let userScr = WKUserScript.init(source: jsstring, injectionTime: .atDocumentEnd, forMainFrameOnly: true);
    

        let realwidth = (SCREEN_WIDTH - 40) * 1.25
        let imageJsstr = "var count = document.images.length;for (var i = 0; i < count; i++) {var image = document.images[i];image.style.width=\(realwidth);};";
        let flashJsstr = "document.flash.witdh = 320";
        
        let flashScr = WKUserScript.init(source: flashJsstr, injectionTime: .atDocumentEnd, forMainFrameOnly: true);
        let imageScr = WKUserScript.init(source: imageJsstr, injectionTime: .atDocumentEnd, forMainFrameOnly: true);
        config.userContentController.addUserScript(userScr);
        config.userContentController.addUserScript(imageScr);
        self.webView = WKWebView.init(frame: .init(x: 20, y: 700, width: SCREEN_WIDTH - 40, height: SCREEN_HEIGHT - 64), configuration: config);

      
        config.userContentController.addUserScript(flashScr);
        
        self.webView.centerX = SCREEN_WIDTH / 2;
        
        self.loadDetailNetWork();
       
        
        
        self.scrollView = UIScrollView.init(frame: .init(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - 64));
        self.scrollView?.addSubview(self.webView!);
        // Do any additional setup after loading the view.
    }

    func configHeaderView() -> Void {
        
        self.bannerImageView = UIImageView.init(frame: .init(x: 25, y: 10, width: SCREEN_WIDTH - 50, height: 0.66 * (SCREEN_WIDTH - 50)));
        self.bannerImageView?.sd_setImage(with: URL.init(string: (detailModel?.cover_url)!), placeholderImage: BannerImage, options: .retryFailed);
        self.scrollView?.addSubview(self.bannerImageView!);
        
        self.playListView = YYMusicPlayListView.init(frame: .init(x: 25, y: (self.bannerImageView?.bottom)! + 30, width: SCREEN_WIDTH - 50, height: 65));
        
        self.playListView?.model = self.detailModel;
        self.playListView?.delegate = self;
        self.scrollView?.addSubview(self.playListView!);
        
        
        self.titileView = YYTitleView.init(frame: .init(x: 25, y: (self.playListView?.bottom)! + 30, width: SCREEN_WIDTH - 50, height: 50));
        self.titileView?.backgroundColor = .clear;
        self.titileView?.model = self.detailModel;
        
        self.scrollView?.addSubview(self.titileView!);
        self.title = self.titileView?.titleLable?.text;
        
    }
    func configFooterView() -> Void {
        
    }
    func cacluteFrame(isShowAll:Bool) -> Void {
        
        self.titileView?.top = (self.playListView?.bottom)! + 30;
        
        
       
        
//        if isShowAll {
//            self.titileView?.top = (self.playListView?.bottom)! + 30 + 40.0 * CGFloat((self.detailModel?.tracks?.count)!);
//        }
        
         self.webView.top = (self.titileView?.bottom)! + 20;
        self.scrollView?.contentSize = CGSize.init(width: SCREEN_WIDTH, height: self.webView.bottom + 100);
        
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func loadDetailNetWork() -> Void {
        
        let time:Int = Int(NSDate().timeIntervalSince1970);
        let url:String = "http://wawa.fm:9090/wawa/api.php/document/getdocument?datatype=jsonp&id=\((model?.id)!)&platform=yyios&callback=data&_=\(time)"
        
        YYYuYinNetWorkManger.defultManger.getNetwork(urlString: url, dic: [:], isJson: false, successHandle: { (json) in
            
            var str = String.init(data: json as! Data, encoding: .utf8);
            
            let index = str?.index((str?.startIndex)!, offsetBy: 6);
            str = str?.substring(from: index!);
            
            
            str = str?.substring(to: (str?.index((str?.endIndex)!, offsetBy: -1))!);
            
            
            let data = str?.data(using: .utf8);
            
            let mydic = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
            
            let model:YYArticleDetailModel = YYArticleDetailModel.mj_object(withKeyValues: mydic);
            
            self.webView.loadHTMLString(model.article.content!, baseURL: nil);
            self.webView.sizeToFit();
            self.webView.navigationDelegate = self;
            
            self.detailModel = model;
            
            
        }) { (failStr) in
            
        }
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        webView.evaluateJavaScript("document.body.offsetHeight") { (result, error) in
            
            let height = result as! CGFloat;
            
            self.scrollView?.contentSize = .init(width: SCREEN_WIDTH, height: height + 200);
            self.webView.height = height;
            self.webView.scrollView.isScrollEnabled = false;
            self.view.addSubview(self.scrollView!);
            
            self.configHeaderView();
            
            self.cacluteFrame(isShowAll: false);
            
        }
        webView.evaluateJavaScript("document.body.scrollWidth") { (result, error) in
            
            let lwidth = result as! CGFloat;
           // var testWitdh:CGFloat = CGFloat();
            
          //  var contentView = self.webView.scrollView.value(forKey: "WKContentView");
          //  var contetView = self.webView.scrollView.value(forKey: "WKContentView");
            
//            for view in self.webView.scrollView.subviews {
//  
//                print("view is \(view)");
//                if view.width > (SCREEN_WIDTH - 40) {
//                
//                    testWitdh = view.width;
//                    break;
//                }
//            }
            
            print("now宽度 \(lwidth) 屏幕宽度\(SCREEN_WIDTH) - 40");
            
            if lwidth > (SCREEN_WIDTH - 40){
            
                let bili = (SCREEN_WIDTH - 40) / lwidth;
                let jsstring = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'minimum-scale=0.1, maximum-scale=2.0,initial-scale=\(bili),width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        
                
                let flashScr = WKUserScript.init(source: jsstring, injectionTime: .atDocumentEnd, forMainFrameOnly: true);
                self.webView.configuration.userContentController.addUserScript(flashScr);

                //self.webView.reload();
            }
            
        }

        
    }

        //MARK:YYMusicPlayListViewDelegate
    
    //点击了播放按钮
    func didClicThePlayView(listView:YYMusicPlayListView) -> Void {
    
    }
    //点击了展开按钮
    func didClicTheShowAllView(listView:YYMusicPlayListView) -> Void {
    
        self.cacluteFrame(isShowAll: (listView.allButton?.isSelected)!);
    }
    //点击了展开列表其中一项
    func didClicTheAllView(listView:YYMusicPlayListView,tag:Int) -> Void {
    
        print("点击了\(tag)");
    }
    

}
